package com.secfound.soccer.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.secfound.soccer.client.gui.ScoreboardGUI;
import com.secfound.soccer.shared.db.Challenger;

/**
 * Entry point for the App.
 * 
 * Checks if user is connected
 * If is connected, show GUI
 * else shows a login link
 * 
 */
public class Soccer implements EntryPoint {
	/**
	 * Create a remote service proxy to talk to the server-side Booking service.
	 */
	private final BettingServiceAsync bookingService = GWT.create(BettingService.class);

	private ScoreboardGUI gui;
	Challenger gamer ;
	private VerticalPanel loginPanel = new VerticalPanel();
	private Label loginLabel = new Label("Please sign in to your Google Account to access the application.");
	private Anchor signInLink = new Anchor("Sign In");

	/* 
	 * Main function
	 *  (non-Javadoc)
	 * @see com.google.gwt.core.client.EntryPoint#onModuleLoad()
	 */
	public void onModuleLoad() {
		final LoginServiceAsync loginService = GWT.create(LoginService.class);
		AsyncCallback<Challenger> acb = new AsyncCallback<Challenger>() {
			public void onFailure(Throwable error) {
				String msg= "Error on Login callback "+ error.getMessage();
				Window.alert(msg);
			}
			@Override
			public void onSuccess(Challenger result) {
				gamer=result;
				if(gamer.isLoggedIn()){
					gui= new ScoreboardGUI();
					gui.init(bookingService, loginService, gamer);
				}else{
					loadLogin(gamer);
				}
			}
		};
		loginService.login(GWT.getHostPageBaseURL(), acb);
	}

	private void loadLogin(Challenger result) {
		signInLink.setHref( result.getLoginURL().toString() );
		loginPanel.add(loginLabel);
		loginPanel.add(signInLink);
		RootPanel.get("mainpanel").add(loginPanel);
	}
}
